from fastapi import FastAPI,Request
import uvicorn
from fastapi.templating import Jinja2Templates
import sqlite3
from fastapi.staticfiles import StaticFiles
from fastapi.responses import RedirectResponse
import urllib

app1=FastAPI()
tem=Jinja2Templates("static/pages")
@app1.get("/")
async def f1(demo:Request):
    return tem.TemplateResponse("index.html",context={"request":demo})
@app1.get("/demo/books")
def f3(keyword:Request):
    txt=urllib.parse.unquote(keyword.url.query.split("=")[-1])
    keyword2=txt.split("-")[1]
    offset=int(txt.split("-")[0])
    print("keyword："+txt)
    con=sqlite3.connect("C:\\Users\\ASUS\\Desktop\\D-Spider\\back\\D-Spider.db")
    cur=con.cursor()
    key='%'+keyword2+'%'
    cur.execute("select * from test_table where name like '"+key+"'")
    data=cur.fetchall()
    cur.close()
    con.close()
    print(len(data))
    page_num=len(data)//5+1
    return tem.TemplateResponse("books.html",context={"request":keyword,"data":data[offset*5:offset*5+5],"page_num":page_num,"current_page_index":offset,"keyword":keyword2})
@app1.get("/demo/detail")
def f2(re:Request):
    name=urllib.parse.unquote(re.url.query.split("=")[-1])
    print("name:"+name)
    con=sqlite3.connect("C:\\Users\\ASUS\\Desktop\\D-Spider\\back\\D-Spider.db")
    cur=con.cursor()
    cur.execute("select * from test_table where name='%s';"%name)
    data=cur.fetchall()
    cur.close()
    con.close()
    print(data)
    return tem.TemplateResponse("detail.html",context={"request":re,"data":data})

if __name__=='__main__':
    uvicorn.run('main:app1', host='127.0.0.1', port=8000, reload=True)

